import 'package:go_router/go_router.dart';
import 'package:flutter/material.dart';
import '../utils/deferred_router.dart';

// 延迟导入页面
import '../pages/home_page.dart' deferred as home;
import '../pages/profile_page.dart' deferred as profile;
import '../pages/settings_page.dart' deferred as settings;

class AppRoutes {
  static void initialize() {
    // 注册延迟加载器
    DeferredRouterManager.registerLoader('home', home.loadLibrary, displayName: 'Home Page');
    DeferredRouterManager.registerLoader('profile', profile.loadLibrary, displayName: 'Profile Page');
    DeferredRouterManager.registerLoader('settings', settings.loadLibrary, displayName: 'Settings Page');
  }

  static final GoRouter router = GoRouter(
    initialLocation: '/menu',
    routes: [
      // 主页路由 - 使用DeferredRoute
      DeferredRoute(
        path: '/',
        name: 'home',
        libraryLoader: home.loadLibrary,
        placeholderName: 'Home Page',
        builder: (context, state) => home.HomePage(),
      ).toGoRoute(),

      // 个人资料页面 - 使用DeferredRouterManager
      DeferredRouterManager.createDeferredRoute(
        path: '/profile',
        name: 'profile',
        loaderName: 'profile',
        placeholderName: 'Profile Page',
        builder: (context, state) => profile.ProfilePage(),
      ),

      // 设置页面 - 带嵌套路由
      DeferredRoute(
        path: '/settings',
        name: 'settings',
        libraryLoader: settings.loadLibrary,
        placeholderName: 'Settings',
        builder: (context, state) => settings.SettingsPage(),
        routes: [
          GoRoute(
            path: '/account',
            name: 'account-settings',
            builder: (context, state) => DeferredPage(
              libraryLoader: settings.loadLibrary,
              placeholderName: 'Account Settings',
              builder: (context) => settings.AccountSettingsPage(),
            ),
          ),
        ],
      ).toGoRoute(),

      // 手动包装的路由示例
      GoRoute(
        path: '/manual',
        name: 'manual',
        builder: (context, state) => DeferredPage(
          libraryLoader: settings.loadLibrary,
          placeholderName: 'Manual Page',
          builder: (context) => settings.ManualPage(),
        ),
      ),

      // 主菜单页面（用于演示导航）
      GoRoute(
        path: '/menu',
        name: 'menu',
        builder: (context, state) => const MenuPage(),
      ),
    ],
  );
}

/// 主菜单页面，用于演示各种路由
class MenuPage extends StatelessWidget {
  const MenuPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Deferred Router Demo'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Card(
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  children: [
                    Icon(Icons.rocket_launch, size: 48, color: Colors.deepPurple),
                    SizedBox(height: 12),
                    Text(
                      'Deferred Loading Demo',
                      style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                    ),
                    SizedBox(height: 8),
                    Text(
                      'This demo showcases deferred loading integration with go_router, based on Flutter Gallery patterns.',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 16, color: Colors.grey),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24),
            const Text(
              'Choose a page to navigate:',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: GridView.count(
                crossAxisCount: 2,
                crossAxisSpacing: 12,
                mainAxisSpacing: 12,
                children: [
                  _buildNavigationCard(
                    context,
                    'Home',
                    Icons.home,
                    Colors.blue,
                    () => context.go('/'),
                  ),
                  _buildNavigationCard(
                    context,
                    'Profile',
                    Icons.person,
                    Colors.purple,
                    () => context.go('/profile'),
                  ),
                  _buildNavigationCard(
                    context,
                    'Settings',
                    Icons.settings,
                    Colors.orange,
                    () => context.go('/settings'),
                  ),
                  _buildNavigationCard(
                    context,
                    'Account',
                    Icons.account_circle,
                    Colors.green,
                    () => context.go('/settings/account'),
                  ),
                  _buildNavigationCard(
                    context,
                    'Manual',
                    Icons.book,
                    Colors.teal,
                    () => context.go('/manual'),
                  ),
                  _buildNavigationCard(
                    context,
                    'Preload All',
                    Icons.download,
                    Colors.red,
                    () => _preloadAll(context),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildNavigationCard(
    BuildContext context,
    String title,
    IconData icon,
    Color color,
    VoidCallback onTap,
  ) {
    return Card(
      elevation: 4,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(icon, size: 32, color: color),
              const SizedBox(height: 8),
              Text(
                title,
                style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _preloadAll(BuildContext context) async {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Preloading all deferred libraries...')),
    );
    
    try {
      await DeferredRouterManager.preloadAll();
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('All libraries preloaded successfully!'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Preload failed: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
}